using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Core;

namespace NHibernateGenerator
{
	public class NHibernateConfigInsertGenerator
	{
		private const string DIRECTORY = @"GeneratedFiles\";

		public NHibernateConfigInsertGenerator()
		{
		}

		public NHibernateConfigInsertGenerator(Assembly assembly)
		{
			this.Assembly = assembly;
		}


		public Assembly Assembly { get; set; }


		public void Execute(IEnumerable<string> selectedClassNames)
		{
			string template = @"<mapping resource=""{DAO_NAMESPACE}.NHibernate.{CLASS_NAME}.hbm.xml"" assembly=""{ASSEMBLY}"" />";

			string overallConfig = "";

			TextWriter writer;

			foreach (string fullName in selectedClassNames) {
				//create a new template string
				string classTemplate = template;

				Type classType = this.Assembly.GetType(fullName);
				string className = classType.Name;

				classTemplate = classTemplate.Replace("{CLASS_NAME}", className);
				classTemplate = classTemplate.Replace("{ASSEMBLY}", this.Assembly.GetName().Name);
				classTemplate = classTemplate.Replace("{DAO_NAMESPACE}", Utilities.GetDaoNameSpace(classType.Namespace));

				overallConfig += Environment.NewLine + classTemplate;
			}

			Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + DIRECTORY);

			writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + DIRECTORY + "hibernate.addition.cfg.xml");

			writer.Write(overallConfig);

			writer.Flush();
			writer.Close();
		}
	}
}